package cqut.wys.websocket;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Websocket拦截器类
 * @author wuyoushan@zbj.com
 * @date 2017/3/20.
 */
public class WebSocketInterceptor implements HandshakeInterceptor {


    /**
     * 调用握手前
     * 将HttpSession中对象放入WebSocketSession中
     * @param request
     * @param response
     * @param wsHandler
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> map) throws Exception {
        if (request instanceof ServerHttpRequest){
            ServletServerHttpRequest servletServerHttpRequest= (ServletServerHttpRequest) request;
            HttpSession session=servletServerHttpRequest.getServletRequest().getSession();
            if(session!=null) {
                if (session.getAttribute("user") != null) {
                    //区分socket连接以定向发送消息
                    map.put("user", session.getAttribute("user"));
                }
            }
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
